package nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import util.FileUtil;

public class FileNIO {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		copyFileByNIO(FileUtil.common_file_path + "testfile.pdf",
				FileUtil.common_file_path + "testfile1.pdf");

	}

	public static void copyFileByNIO(String source, String target) {
		long begintime = System.currentTimeMillis();
		File sourceFile = new File(source);
		if (!sourceFile.exists() || !sourceFile.isFile()) {
			return;
		}
		File targetFile = new File(target);
		FileInputStream is = null;
		FileOutputStream os = null;
		try {
			is = new FileInputStream(sourceFile);
			os = new FileOutputStream(targetFile);
			FileChannel inChanl = is.getChannel();
			FileChannel outChanel = os.getChannel();
			ByteBuffer buff = ByteBuffer.allocate(1024);
			while (true) {
				//clear重置缓冲区，准备接受数据
				buff.clear();
				int r = inChanl.read(buff);
				if (r == -1) {
					break;
				}
				//准备将数据写入另一个通道
				buff.flip();
				outChanel.write(buff);
			}
			long endtime = System.currentTimeMillis();
			System.out.println("cost time " + (endtime - begintime) + " mm");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

}
